# -*- coding: utf-8 -*-
'''
@author: olivia.dou
Created on: 3/17/2021 18:19
desc: 标准化业务相关代码
'''
import logging
import traceback

from util.db_util import execute_query


def get_std_biz_info(**kwargs):
    """根据不同的分类 业务查询业务基本信息

    :param kwargs:
        | client_code: 分类code
        | biz_code: 业务code
        | non_financial:是否为non_financial业务：0否，1是

    :return: 业务基本信息
    """
    if "client_code" in kwargs and "biz_code" in kwargs:
        condition = "where client_code='%s' AND `biz_code`='%s'" % (kwargs['client_code'], kwargs['biz_code'])
    elif "id" in kwargs:
        condition = "where id=%s"%kwargs['id']
    elif "non_financial" in kwargs:
        condition = "where non_financial=%s and status=0" % kwargs['non_financial']
    else:
        logging.error("get_std_biz_info: id / (client code+biz code) / (client_code + biz_name) / non-financial required!")
        return None

    sql = "select * from t_das_std_biz %s"%condition

    try:
        # res = execute_query(sql)
        # biz_info = pd.Series(res[0],index=['id','client_code','biz_code','biz_name','tbl_name','group_name','restate_type','status'])
        res = execute_query(sql, result_type="dict")
        biz_info = res if "non_financial" in kwargs else res[0] if len(res)>0 else None
        return biz_info
    except Exception as e:
        logging.error(e)
        traceback.print_exc()
        return None


def get_std_biz_id(client_code, biz_code):
    """获取指定分类 业务的id

    :param client_code: 分类code
    :param biz_code: 业务code

    :return: 业务id
    """
    # results = execute_query(
    #     "SELECT id FROM `t_das_std_biz` WHERE client_code='%s' AND `biz_code`='%s'" % (client_code, biz_code))
    # try:
    #     result = results[0][0]
    #     return result
    # except Exception as e:
    #     logging.error("no result retrieved")
    #     return None

    biz_info = get_std_biz_info(client_code=client_code, biz_code=biz_code)
    if biz_info is not None:
        return biz_info['id']
    else:
        return -1


def get_std_biz_ids(tbl_name):
    """获取指定表名下业务id列表

    :param tbl_name: 表名

    :return: 业务id列表
    """
    res = execute_query(
        "SELECT id FROM `t_das_std_biz` WHERE tbl_name='%s' and status=0" % tbl_name)
    try:
        results = [res[i][0] for i in range(len(res))]
        return results
    except Exception as e:
        logging.error("get_std_biz_ids:%s" % e)
        return None


def get_std_biz_tbl_col_ids(biz_code, **kwargs):
    """获取指定条件下业务绑定数据列id列表

    :param biz_code: 业务编码
    :param kwargs:
        | std_field：数据存储字段

    :return: 业务绑定数据列id列表
    """

    if "std_field" in kwargs:
        results = execute_query("SELECT b.std_col_id FROM `t_das_std_biz_tbl_col` b "
                                "LEFT JOIN t_das_std_tbl_col c ON b.std_col_id=c.id WHERE b.`biz_code` = '%s' AND c.std_field='%s'" % (
                                    biz_code, kwargs["std_field"]))
        result = [results[i][0] for i in range(len(results))]
    else:
        results = execute_query("SELECT id FROM `t_das_std_biz_tbl_col` WHERE `biz_code` = '%s'" % biz_code)
        result = [results[i][0] for i in range(len(results))]
    try:
        return result
    except Exception as e:
        logging.error("get_std_biz_tbl_col_ids:%s" % e)
        return None


def get_std_biz_tbl_col_id(biz_code, **kwargs):
    """获取指定条件下业务绑定数据列id

    :param biz_code: 业务编码
    :param kwargs:
        | std_col_id：标准数据列id

    :return: 业务绑定数据列id
    """
    try:
        if "std_col_id" in kwargs:
            results = execute_query(
                "SELECT id FROM `t_das_std_biz_tbl_col` WHERE `biz_code` = '%s' AND `std_col_id` = '%s'" % (
                    biz_code, kwargs["std_col_id"]))
            result = results[0][0]
            return result
        else:
            return None
    except Exception as e:
        logging.error("get_StdBizTblCol_id:%s" % e)
        return None


def get_std_biz_element_info(biz_code):
    """获取业务关联的模型元素

    :param biz_code: 业务code

    :return: 业务关联的模型元素信息
    """
    res = execute_query(
        "SELECT * FROM t_das_std_biz_element WHERE biz_code='%s'" % biz_code,result_type="dict")
    try:
        return res
    except Exception as e:
        logging.error("get_std_biz_element_info failed, biz_code: %s"%biz_code)
        return None

def get_biz_code_from_element(model_id,element_id):
    """获取业务关联的模型元素

    :param model_id: 模型id
        :param element_id: 元素id

    :return: 业务code
    """
    res = execute_query(
        "SELECT * FROM `das`.`t_das_std_biz_element` WHERE `model_id` = '%s' AND `element_id` = '%s'" % (model_id,element_id),result_type="dict")
    try:
        return res[0]['biz_code']
    except Exception as e:
        logging.error("get_std_biz_element_info failed, biz_code: %s"%e)
        return None


def get_biz_std_table_name(client_code,biz_code):
    """获取指定客户编码、业务编码对应业务的标准化表名
    Todo: 改为调用get_std_biz_info

    :param client_code: 客户编码
    :param biz_code: 业务编码

    :return: 指定客户编码、业务编码对应业务的标准化表名
    """
    sql = """select tbl_name from t_das_std_biz where client_code='%s' and biz_code='%s'""" % (client_code,biz_code)
    try:
        res = execute_query(sql)
        table_name = res[0][0]
        return table_name
    except Exception as e:
        logging.error(e)
        traceback.print_exc()
        return ''